//
//  CommonTool.m
//  cocoapodText
//
//  Created by apple on 16/9/19.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "CommonTool.h"
#import "AppDelegate.h"
@implementation CommonTool

+ (void)showAllTextDialogWithText:(NSString *)text parentView:(UIView *)view{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
    // Set the text mode to show only text.
    HUD.mode = MBProgressHUDModeText;
    HUD.label.text = NSLocalizedString(text, @"HUD message title");
    // Move to bottm center.
    HUD.offset = CGPointMake(0.f, 0.f);
    [HUD hideAnimated:YES afterDelay:2.f];
}

+ (void)showAllTextDialogInTopWithText:(NSString *)text parentView:(UIView *)view{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
    // Set the text mode to show only text.
    HUD.mode = MBProgressHUDModeText;
    HUD.label.text = NSLocalizedString(text, @"HUD message title");
    // Move to bottm center.
    HUD.offset = CGPointMake(0.f, -MBProgressMaxOffset);
    [HUD hideAnimated:YES afterDelay:2.f];
}

+ (void)showAllTextDialogInBottomWithText:(NSString *)text parentView:(UIView *)view{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:view animated:YES];
    // Set the text mode to show only text.
    HUD.mode = MBProgressHUDModeText;
    HUD.label.text = NSLocalizedString(text, @"HUD message title");
    // Move to bottm center.
    HUD.offset = CGPointMake(0.f, -MBProgressMaxOffset);
    [HUD hideAnimated:YES afterDelay:2.f];
}

+(Boolean)isHaveValue:(NSString *)key{
    if ([[NSUserDefaults standardUserDefaults ]valueForKey:key]==nil) {
        return NO;
    }
    return YES;
}

+(NSString *)getValueFromKey:(NSString *)key defaultValue:(NSString *)value{
    NSString *temObj;
    if ([self isHaveValue:key]) {
        temObj= [[NSUserDefaults standardUserDefaults ]valueForKey:key];
    }else{
        temObj=value;
    }
    return temObj;
}

+(void)updateValueWithKey:(NSString *)key value:(NSString *)key_value{
    [[NSUserDefaults standardUserDefaults ] setObject:key_value forKey:key];
}

+(NSString *)getStringFromNSDictionary:(NSDictionary *)obj key:(NSString *)key defaultValue:(NSString *)value{
    NSString *trueValue;
    if(obj!=nil&&![obj isEqual:[NSNull null]]){
        if ([[obj allKeys] containsObject:key]){
            if ([[obj objectForKey:key] isKindOfClass:[NSNumber class]]) {
                NSNumber *temNumber=[obj objectForKey:key];
                trueValue = temNumber.description;
            }else{
                trueValue=[obj objectForKey:key];
            }
            if (trueValue==nil) {
                trueValue=value;
            }else if([trueValue isEqual:[NSNull null]]){
                trueValue=value;
            }
        }else{
            trueValue=value;
        }
        return trueValue;
    }else{
        return value;
    }
}

+(int)NSIntegerToInt:(NSInteger )integer{
    return [[NSString stringWithFormat:@"%ld",(long)integer] intValue];
}

+(NSString *)getStringFromNSArray:(NSArray *)obj key:(int)key{
    NSString *trueValue;
    if ([[obj objectAtIndex:key] isKindOfClass:[NSNumber class]]) {
        NSNumber *temNumber=[obj objectAtIndex:key];
        trueValue = temNumber.description;
    }else{
        trueValue=[obj objectAtIndex:key];
    }
    return trueValue;
}

+(NSDate *)StringToDate:(NSString *)dateStr rule:(NSString *)rule{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:rule];
    return [inputFormatter dateFromString:dateStr];
}

+(NSString *)getNowDateTime{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    return [NSString stringWithFormat:@"%f", a];//转为字符型
}

+(NSString *)getNowDateTimeByTimestamp:(NSString *)timestamp Rule:(NSString *)rule{
    //时间戳转时间的方法:
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:rule];
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]/ 1000.0];
    return [formatter stringFromDate:date];
}

+(NSString *)getNowDateWithRule:(NSString *)rule{
    NSDate *date=[NSDate date];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:rule];
    return [inputFormatter stringFromDate:date];
}

+(NSString *)getDateTimeDifferenceWithYear:(int)year Month:(int)month Day:(int)day Rule:(NSString *)rule{
    NSDate *mydate=[NSDate date];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:rule];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = nil;
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:mydate];
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setYear:year];
    [adcomps setMonth:month];
    [adcomps setDay:day];
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
    
    return [inputFormatter stringFromDate:newdate];
}

+(NSString *)getDateTimeDifferenceWithYear:(int)year Month:(int)month Day:(int)day Rule:(NSString *)rule Date:(NSDate *)date{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:rule];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = nil;
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setYear:year];
    [adcomps setMonth:month];
    [adcomps setDay:day];
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:date options:0];
    
    return [inputFormatter stringFromDate:newdate];
}


+(int)getGreaterThanOrEqualToNumWithDivisor:(int)divisor Dividend:(int)dividend{
    int a=divisor/dividend;
    int b=divisor%dividend;
    if (b==0) {
        return a;
    }
    return a+1;
}

+(bool)isLoginExpired{
    NSString *shangciLoginTime=[self getValueFromKey:@"loginInTime" defaultValue:@""];
    NSDate *start = [CommonTool StringToDate:shangciLoginTime rule:@"yyyyMMddHHmmss"];
    NSDate *end = [NSDate date];
    NSTimeInterval timeBetween = [end timeIntervalSinceDate:start];
    if (timeBetween>0) {
        int hour = (int)(timeBetween/3600);
        int minute = (int)(timeBetween - hour*3600)/60;
        //int second = timeBetween - hour*3600 - minute*60;
        if (hour>0) {
            return YES;
        }else{
            if (minute>30) {
                return YES;
            }
        }
        return NO;
    }else{
        return YES;
    }
}

+(NSString *)keepDecimal:(NSString *)str{
    if (![self isPureNum:str]) {
        return str;
    }
    if ([self isPureInt:str]) {
        return str;
    }
    
    CGFloat num=[str floatValue];
    NSString *temStr=[NSString stringWithFormat:@"%.1lf",num];
    if ([temStr isEqualToString:str]) {
        return str;
    }
    str=[NSString stringWithFormat:@"%.2lf",num];
    return str;
}


//判断是否为整形：
+(BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}


//判断是否为浮点形：
+(BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}


//判断是否是纯数字
+(BOOL)isPureNum:(NSString *)string{
    if ([self isPureInt:string]) {
        return YES;
    }
    
    if ([self isPureFloat:string]) {
        return YES;
    }
    return NO;
}

+(void)isSessionExpired:(NSURLSessionDataTask *)task{
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
    NSDictionary *allHeaders = response.allHeaderFields;
    NSString *srcStr = [allHeaders objectForKey:@"Set-Cookie"];
    NSArray *strarray = [srcStr componentsSeparatedByString:@";"];
    NSString *JSESSIONID_ALL=strarray[0];
    NSArray *strarray_j = [JSESSIONID_ALL componentsSeparatedByString:@"="];
    NSString *JSESSIONID=strarray_j[1];
    if (![JSESSIONID isEqualToString:[self getValueFromKey:@"JSESSIONID" defaultValue:@""]]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SessionExpired" object:nil];
    }
}

+(NSString *)addXiaoShuDian:(NSString *)num{
    if ([self isPureNum:num]) {
        if ([self isPureInt:num]) {
            CGFloat numFloat=[num floatValue];
            return [NSString stringWithFormat:@"%.2lf",numFloat];
        }else{
            return num;
        }
    }else{
        return num;
    }
}

//UIColor 转UIImage
+(UIImage*) createImageWithColor: (UIColor*) color Frame:(CGRect)frame
{
    CGRect rect=frame;
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}


//UIImage转UIColor
+(UIColor *)createColorWhiteImage:(NSString *)image{
    return [UIColor colorWithPatternImage:[UIImage imageNamed:image]];
}
@end
